/*
 * @Date: 2022-12-26 15:26:48
 * @LastEditors: 旧轩00°°
 * @LastEditTime: 2022-12-27 17:14:24
 * @FilePath: /vue3-ts-vite-pinia-husky/src/utils/cache.ts
 */
import { defaultSetting } from '@/config/setting'
const { PREFIX_NAME } = defaultSetting

const prefixKey = PREFIX_NAME ? PREFIX_NAME + '_' : ''
class Cache {
  storage: Storage

  constructor(type: string) {
    this.storage =
      type.toLocaleLowerCase() == 'local' ? localStorage : sessionStorage
  }

  setCache(key: string, value: any) {
    if (value) {
      this.storage.setItem(
        prefixKey + key,
        typeof value === 'string' ? value : JSON.stringify(value)
      )
    }
  }

  getCache(key: string) {
    const local = this.storage.getItem(prefixKey + key)
    let result = null
    try {
      result = JSON.parse(local)
    } catch (error) {
      // 报错证明local不是对象，不需要转义
      result = local
    }
    return result
  }

  remove(key: string) {
    this.storage.removeItem(key)
  }

  clear() {
    this.storage.clear()
  }
}

export default Cache
